package com.dgut.Service;

import com.dgut.model.RegionConfirm;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVRecord;
import org.springframework.core.io.Resource;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;

@Service
public class DataService {
    private List<RegionConfirm> allRegionConfirms ;
    private String CORONA_VIRUS_DATA_URL = "https://gitee.com/dgut-sai/COVID-19/raw/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv";

    //爬取并解析数据
    public void getRegionData() throws IOException{
        //爬取数据
        RequestEntity requestEntity = RequestEntity
                .get(URI.create(CORONA_VIRUS_DATA_URL))
                .headers(httpHeaders -> httpHeaders.add("User-Agent","Mozilla/5.0"))
                .build();
        ResponseEntity<Resource> exchange = new RestTemplate().exchange(requestEntity,Resource.class);
        Resource body = exchange.getBody();

        //解析csv
        allRegionConfirms = new ArrayList<>();   //将数据清空
        Reader reader = new InputStreamReader(body.getInputStream());
        Iterable<CSVRecord> records = CSVFormat.RFC4180.withFirstRecordAsHeader().parse(reader);
        for (CSVRecord record : records) {
            RegionConfirm confirm = new RegionConfirm();
            confirm.setState(record.get("Province/State"));
            confirm.setCountry(record.get("Country/Region"));
            long total = 0;
            for (int i = 4; i < record.size(); i++) {
                total += Long.parseLong(record.get(i));
            }
            confirm.setLatestTotalCases(total);
            confirm.setDiffFromPreDay(Integer.parseInt(record.get(record.size() - 1)));
            allRegionConfirms.add(confirm);
        }
    }

    public List<RegionConfirm> getAllRegionConfirms(){
        return allRegionConfirms;
    }

}
